package com.chenjun.web.controller.activiti;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.javax.el.ExpressionFactory;
import org.activiti.engine.impl.javax.el.ValueExpression;
import org.activiti.engine.impl.juel.ExpressionFactoryImpl;
import org.activiti.engine.impl.juel.SimpleContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chenjun.common.base.ResultDto;
import com.chenjun.common.bean.Pagination;
import com.chenjun.common.model.DataGridModelUnPaginationInterceptor;
import com.chenjun.common.util.DateJsonValueProcessor;
import com.chenjun.core.dao.generator.entity.OaBillLeaveApplication;
import com.chenjun.core.dao.generator.entity.OaBillOvertimeApplication;
import com.chenjun.core.dao.generator.entity.SysUser;
import com.chenjun.core.service.oa.LeaveManagerService;
import com.chenjun.core.service.oa.OvertimeManagerService;
import com.chenjun.core.service.sys.SysUserService;
import com.chenjun.core.vo.activiti.MyTaskDto;
import com.chenjun.web.controller.BaseController;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@SuppressWarnings("serial")
@Controller
@RequestMapping("/process/task")
public class TaskController extends BaseController {
	
	@Resource
	private TaskService taskService;
	
	@Resource
	private RuntimeService runtimeService;
	
	@Resource
	private RepositoryService repositoryService;
	
	@Resource
	private HistoryService historyService;
	
	@Autowired
	private LeaveManagerService leaveService;
	
	@Autowired
	private OvertimeManagerService overtimeService;
	
	@Autowired
	private SysUserService userService;

	/**
	 * 待办任务页面展示
	 * 
	 * @return ModelAndView
	 */
	@RequestMapping("/list.html")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView("activiti/process/task/list");
		return mv;
	}
	
	/**
	 * 历史任务页面展示
	 * @return
	 */
	@RequestMapping("/history/list.html")
	public ModelAndView historyList() {
		ModelAndView mv = new ModelAndView("activiti/process/task/history-list");
		return mv;
	}
	
	/**
	 * 已办页面展示
	 * @return
	 */
	@RequestMapping("/treated/list.html")
	public ModelAndView treatedList() {
		ModelAndView mv = new ModelAndView("activiti/process/task/treated-list");
		return mv;
	}
	
	/**
	 * 分页查询待办任务
	 * @param datagrid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/search")
	public void getTaskListPage(DataGridModelUnPaginationInterceptor datagrid, HttpServletResponse response) throws Exception{
		SysUser loginUser = getLoginUser();
		int rows = datagrid.getRows();
		int page = datagrid.getPage();
		int start = datagrid.getStart();
		Map<String, Object> params = datagrid.getParams();
		String applyer = params.isEmpty() ? "" : params.get("applyer").toString().trim();
		
		ResultDto rtDto = new ResultDto();
		//当前页
		int pageNo = start / rows;
		//取得总数量
		long taskCount=taskService.createTaskQuery().taskCandidateUser(loginUser.getId()).count();
		
		List<Task> taskList = taskService.createTaskQuery().taskCandidateUser(loginUser.getId()).listPage(pageNo, rows);
		
		List<MyTaskDto> MyTaskList=new ArrayList<MyTaskDto>();
		for(Task t:taskList){
			MyTaskDto myTask=new MyTaskDto();
			myTask.setId(t.getId());
			myTask.setKey(t.getTaskDefinitionKey());
			myTask.setName(t.getName());
			myTask.setProcessDefinitionId(t.getProcessDefinitionId());
			myTask.setCreateTime(t.getCreateTime());
			Integer billID = Integer.valueOf(taskService.getVariable(t.getId(), "billID").toString());
			myTask.setBillID(billID);
			String processDefinitionId = t.getProcessDefinitionId();
			if(processDefinitionId.contains("leave")){
				myTask.setProcessName("请假申请");
				OaBillLeaveApplication leave = leaveService.get(billID);
				myTask.setApplyer(leave.getEmplName());
				if(StringUtils.isNotBlank(applyer) && !leave.getEmplName().equals(applyer)){
					continue;
				}
			}else if(processDefinitionId.contains("overtime")){
				myTask.setProcessName("加班申请");
				OaBillOvertimeApplication overtime = overtimeService.get(billID);
				myTask.setApplyer(overtime.getEmplName());
				if(StringUtils.isNotBlank(applyer) && !overtime.getEmplName().equals(applyer)){
					continue;
				}
			}
			MyTaskList.add(myTask);
		}
		
		Pagination data = new Pagination();
		data.setAaData(MyTaskList);
		data.setiTotalDisplayRecords((int)taskCount);
		data.setiTotalLongRecords(taskCount);
		data.setiTotalRecords((int)taskCount);
		data.setsEcho(page);
		rtDto.setData(data);
		
		genResponse(response, rtDto);
	}
	
	/**
	 * 审批
	 * @param taskId 任务id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/submitTask")
	@ResponseBody
	public ResultDto submitTask(String taskId, Integer state, String comment, @RequestParam("leaderships[]") List<String> leaderships)throws Exception{
		ResultDto rtDto = new ResultDto();
		//首先根据ID查询任务
		Task task=taskService.createTaskQuery() // 创建任务查询
		        .taskId(taskId) // 根据任务id查询
		        .singleResult();
		
		Map<String,Object> variables=new HashMap<String,Object>();
		//取得角色用户登入的session对象
		SysUser loginUser = getLoginUser();
		if(state==1){
			variables.put("msg", "同意");
		}else{
			variables.put("msg", "不同意");
		}
		
		// TODO 指定下一处理人
		if(leaderships.size() > 0 && !leaderships.get(0).equals("")){
			variables.put("leaderships", leaderships);
		}
		
		// 将流程中的天数变量传递到任务中
		//variables.put("days", taskService.getVariable(taskId, "days").toString());
		
		// 获取业务ID
		Integer billID = Integer.valueOf(taskService.getVariable(taskId, "billID").toString());
		 // 获取流程实例id
		String processInstanceId=task.getProcessInstanceId();
		// 设置用户id
		Authentication.setAuthenticatedUserId(loginUser.getId()); 
		// 添加批注信息
		taskService.addComment(taskId, processInstanceId, comment); 
		// 完成任务
		taskService.complete(taskId, variables); 
		
		// 处理关联单据
		ProcessInstance pi = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId).singleResult();
		String processDefinitionId = task.getProcessDefinitionId();
		if(processDefinitionId.contains("leave")){
			OaBillLeaveApplication leave = leaveService.get(billID);
			if(pi == null){
				// 流程结束
				if(state==1){
					leave.setStatus(40);// 已同意
				}else{
					leave.setStatus(50);// 已驳回
				}
			}else{
				leave.setStatus(30);// 审核中
			}
			leaveService.createOrUpdate(leave);
		}else if(processDefinitionId.contains("overtime")){
			OaBillOvertimeApplication overtime = overtimeService.get(billID);
			if(pi == null){
				// 流程结束
				if(state==1){
					overtime.setStatus(40);// 已同意
				}else{
					overtime.setStatus(50);// 已驳回
				}
			}else{
				overtime.setStatus(30);// 审核中
			}
			overtimeService.createOrUpdate(overtime);
		}
		return rtDto;
	}
	
	/**
	 * 获取下一个流程节点，主要用于判断流程是否结束
	 * @param taskId
	 * @param elKey
	 * @param elParam
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getNextTask")
	@ResponseBody
    public ResultDto getNextTask(String taskId, String elKey, String elParam) throws Exception {  
		ResultDto rtDto = new ResultDto();  
		
		taskService.setVariable(taskId, elKey, elParam);
		
        ProcessDefinitionEntity processDefinitionEntity = null;  
          
        String id = null;  
          
        TaskDefinition task = null;  
          
        //获取流程实例Id信息   
        String processInstanceId = taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId();  
          
        //获取流程发布Id信息   
        String definitionId = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult().getProcessDefinitionId();  
          
        processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)  
                .getDeployedProcessDefinition(definitionId);  
          
        ExecutionEntity execution = (ExecutionEntity) runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();  
          
        //当前流程节点Id信息   
        String activitiId = execution.getActivityId();    
          
        //获取流程所有节点信息   
        List<ActivityImpl> activitiList = processDefinitionEntity.getActivities();   
          
        //遍历所有节点信息   
        for(ActivityImpl activityImpl : activitiList){      
            id = activityImpl.getId();     
              
            // 找到当前节点信息  
            if (activitiId.equals(id)) {  
                  
                //获取下一个节点信息   
                task = nextTaskDefinition(activityImpl, activityImpl.getId(), processInstanceId);  
  
                break;  
            }  
        }  
        if(task != null){
        	rtDto.setData(task.getKey());  
        }else{
        	rtDto.setData("");  
        }
        return rtDto;  
    }  
      
    /**
     * 下一个任务节点信息
     * @param activityImpl
     * @param activityId
     * @param processInstanceId
     * @return
     */
    private TaskDefinition nextTaskDefinition(ActivityImpl activityImpl, String activityId, String processInstanceId){   
              
        PvmActivity ac = null;  
          
        Object s = null;  
          
        //如果遍历节点为用户任务并且节点不是当前节点信息   
        if(("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId()))){    
            //获取该节点下一个节点信息   
            TaskDefinition taskDefinition = ((UserTaskActivityBehavior)activityImpl.getActivityBehavior()).getTaskDefinition();    
            return taskDefinition;    
        }else if("endEvent".equals(activityImpl.getProperty("type"))){
        	//流程结束返回NULL
        	return null;
        }else{    
            //获取节点所有流向线路信息   
            List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();    
            List<PvmTransition> outTransitionsTemp = null;    
            for(PvmTransition tr : outTransitions){ 
            	if(activityId.equals(activityImpl.getId())){
            		 // 如果活动节点为当前任务节点，获取流向节点用于下面判断  
            		ac = tr.getDestination();
            	}else{
            		 // 如果活动节点不为当前任务节点，则活动节点用于下面判断  
            		ac = activityImpl;
            	}
                //如果流向线路为排他网关   
                if("exclusiveGateway".equals(ac.getProperty("type"))){    
                    outTransitionsTemp = ac.getOutgoingTransitions();  
                      
                    //如果排他网关只有一条线路信息   
                    if(outTransitionsTemp.size() == 1){    
                        return nextTaskDefinition((ActivityImpl)outTransitionsTemp.get(0).getDestination(), activityId, processInstanceId);    
                    }else if(outTransitionsTemp.size() > 1){  //如果排他网关有多条线路信息   
                        for(PvmTransition tr1 : outTransitionsTemp){    
                            s = tr1.getProperty("conditionText");  //获取排他网关线路判断条件信息   
                            String elString = s.toString().trim();
                            //根据表达表${}获取参数名
                            String paramName = getParamByElString(elString);
                            //获取流程启动时设置的网关判断条件信息   
                            String elParam = getGatewayCondition(paramName, processInstanceId);
                            //判断el表达式是否成立   
                            if(isCondition(paramName, elString, elParam)){
                                return nextTaskDefinition((ActivityImpl)tr1.getDestination(), activityId, processInstanceId);    
                            }    
                        }    
                    }    
                }else if("userTask".equals(ac.getProperty("type"))){    
                    return ((UserTaskActivityBehavior)((ActivityImpl)ac).getActivityBehavior()).getTaskDefinition();    
                }else if("endEvent".equals(ac.getProperty("type"))){
                	return null;
                }else{  
                	throw new RuntimeException("ActivityImpl: 只支持用户任务、排他网关、结束节点的流向判断");
                }    
            }     
            return null;    
        }    
    }  
      
    /** 
     * 查询流程启动时设置排他网关判断条件信息  
     * @param String gatewayId          排他网关Id信息, 流程启动时设置网关路线判断条件key为网关Id信息  
     * @param String processInstanceId  流程实例Id信息  
     * @return 
     */  
    public String getGatewayCondition(String gatewayId, String processInstanceId) {  
        Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).singleResult();  
        return runtimeService.getVariable(execution.getId(), gatewayId).toString();  
    }  
      
    /** 
     * 根据key和value判断el表达式是否通过信息  
     * @param String key    el表达式key信息  
     * @param String el     el表达式信息  
     * @param String value  el表达式传入值信息  
     * @return 
     */  
    public boolean isCondition(String key, String el, String value) {  
        ExpressionFactory factory = new ExpressionFactoryImpl();    
        SimpleContext context = new SimpleContext();    
        context.setVariable(key, factory.createValueExpression(value, String.class));    
        ValueExpression e = factory.createValueExpression(context, el, boolean.class);    
        return (Boolean) e.getValue(context);  
    }
    
    // 获取参数名
    private static String getParamByElString(String elString){
    	String paramName;
    	if(StringUtils.isNotBlank(elString)){
    		try {
    			 paramName = elString.substring(elString.indexOf("{")+1, elString.indexOf("}"));
    			 if(paramName.contains("<")){
    				 paramName = paramName.substring(0, paramName.indexOf("<"));
    			 }else if(paramName.contains(">")){
    				 paramName = paramName.substring(0, paramName.indexOf(">"));
    			 }else if(paramName.contains("=")){
    				 paramName = paramName.substring(0, paramName.indexOf("="));
    			 }else{
    				 throw new RuntimeException("ActivityImpl: 获取参数名失败,暂不支持该表达式");
    			 }
			} catch (Exception e) {
				throw new RuntimeException("ActivityImpl: 获取参数名失败" + e.toString());
			}
    	}else{
    		throw new RuntimeException("ActivityImpl: 获取参数名失败，表达式为空");
    	}
    	return paramName.trim();
    }
    
    /**
	 * 查询历史流程批注
	 * 
	 * @param response
	 * @param processInstanceId
	 *            流程ID
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/listHistoryCommentWithProcessInstanceId")
	public void listHistoryCommentWithProcessInstanceId(String processInstanceId, HttpServletResponse response) throws Exception {
		ResultDto rtDto = new ResultDto();
		List<Comment> commentList = taskService
				.getProcessInstanceComments(processInstanceId);
		// 改变顺序，按原顺序的反向顺序返回list
		Collections.reverse(commentList); //集合元素反转
		rtDto.setData(commentList);
		genResponse(response, rtDto);
	}
	
	/**
	 * 查询当前流程图
	 * @return
	 */
	@RequestMapping("/showCurrentView")
	public String showCurrentView(HttpServletResponse response,String taskId){
		//视图
		ModelAndView mav=new ModelAndView();
		
		Task task=taskService.createTaskQuery() // 创建任务查询
				.taskId(taskId) // 根据任务id查询
				.singleResult(); 
		 // 获取流程定义id
		String processDefinitionId=task.getProcessDefinitionId();
		ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery() // 创建流程定义查询
				// 根据流程定义id查询
				.processDefinitionId(processDefinitionId) 
				.singleResult(); 
		// 部署id
		mav.addObject("deploymentId",processDefinition.getDeploymentId()); 
		mav.addObject("diagramResourceName", processDefinition.getDiagramResourceName()); // 图片资源文件名称
		
	    ProcessDefinitionEntity	processDefinitionEntity=(ProcessDefinitionEntity) 
	    		repositoryService.getProcessDefinition(processDefinitionId); 
	    // 获取流程实例id
	    String processInstanceId=task.getProcessInstanceId(); 
	    // 根据流程实例id获取流程实例
	    ProcessInstance pi=runtimeService.createProcessInstanceQuery() 
	    		.processInstanceId(processInstanceId)
	    		.singleResult();
	    
	    // 根据活动id获取活动实例
	    ActivityImpl activityImpl=processDefinitionEntity.findActivity(pi.getActivityId()); 
	    //整理好View视图返回到显示页面
	    mav.addObject("x", activityImpl.getX()); // x坐标
	    mav.addObject("y", activityImpl.getY()); // y坐标
	    mav.addObject("width", activityImpl.getWidth()); // 宽度
	    mav.addObject("height", activityImpl.getHeight()); // 高度
		mav.setViewName("page/currentView");
		return null;
	}
	/**
	 * 查询历史批注
	 * @param response
	 * @param taskId 流程ID  
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/listHistoryComment")
	public void listHistoryComment(HttpServletResponse response,String taskId) throws Exception{
		ResultDto rtDto = new ResultDto();
		HistoricTaskInstance hti=historyService.createHistoricTaskInstanceQuery()
				.taskId(taskId)
				.singleResult();
		List<Comment> commentList = new ArrayList<Comment>();
		if(hti!=null){
		    commentList=taskService.getProcessInstanceComments(hti.getProcessInstanceId()); 
			// 集合元素反转
			Collections.reverse(commentList); 
		}
		List<Map<String, Object>> comments = new ArrayList<Map<String, Object>>();
		for(Comment comment : commentList){
			Map<String, Object> ct = new HashMap<String, Object>();
			SysUser user = userService.get(comment.getUserId());
			String userName = user != null ? user.getUserName() : "'未指定'";
			ct.put("time", comment.getTime());
			ct.put("userName", userName);
			ct.put("message", comment.getFullMessage());
			comments.add(ct);
		}
		rtDto.setData(comments);
		genResponse(response, rtDto);
	}
	
	/**
	 * 查詢已办任务列表
	 * @param response
	 * @param rows
	 * @param page
	 * @param s_name  
	 * @param groupId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/treated/search")
	public void treatedList(DataGridModelUnPaginationInterceptor datagrid, HttpServletResponse response) throws Exception{
		SysUser loginUser = getLoginUser();
		int rows = datagrid.getRows();
		int page = datagrid.getPage();
		int start = datagrid.getStart();
		Map<String, Object> params = datagrid.getParams();
		String applyer = params.isEmpty() ? "" : params.get("applyer").toString().trim();
		
		ResultDto rtDto = new ResultDto();
		//当前页
		int pageNo = start / rows;
											//创建流程历史实例查询
		List<HistoricTaskInstance> histList=historyService.createHistoricTaskInstanceQuery()
				.taskCandidateUser(loginUser.getId()).finished()//根据角色名称查询
				.listPage(pageNo, rows);
		
		long histCount=historyService.createHistoricTaskInstanceQuery()
				.taskCandidateUser(loginUser.getId()).finished()
				.count();
		List<MyTaskDto> myTaskList=new ArrayList<MyTaskDto>();
		//这里递出没有用的字段，免得给前端页面做成加载压力
		for(HistoricTaskInstance t:histList){
			MyTaskDto myTask=new MyTaskDto();
			myTask.setId(t.getId());
			myTask.setKey(t.getTaskDefinitionKey());
			myTask.setName(t.getName());
			myTask.setProcessDefinitionId(t.getProcessDefinitionId());
			myTask.setCreateTime(t.getStartTime());
			myTask.setEndTime(t.getEndTime());
			HistoricVariableInstance variable = historyService.createHistoricVariableInstanceQuery().processInstanceId(t.getProcessInstanceId()).variableName("billID").singleResult();
			Integer billID = Integer.valueOf(variable.getValue().toString());
			myTask.setBillID(billID);
			String processDefinitionId = t.getProcessDefinitionId();
			if(processDefinitionId.contains("leave")){
				myTask.setProcessName("请假申请");
				OaBillLeaveApplication leave = leaveService.get(billID);
				myTask.setApplyer(leave.getEmplName());
				if(StringUtils.isNotBlank(applyer) && !leave.getEmplName().equals(applyer)){
					continue;
				}
			}else if(processDefinitionId.contains("overtime")){
				myTask.setProcessName("加班申请");
				OaBillOvertimeApplication overtime = overtimeService.get(billID);
				myTask.setApplyer(overtime.getEmplName());
				if(StringUtils.isNotBlank(applyer) && !overtime.getEmplName().equals(applyer)){
					continue;
				}
			}
			myTaskList.add(myTask);
		}
		Pagination data = new Pagination();
		data.setAaData(myTaskList);
		data.setiTotalDisplayRecords((int)histCount);
		data.setiTotalLongRecords(histCount);
		data.setiTotalRecords((int)histCount);
		data.setsEcho(page);
		rtDto.setData(data);
		genResponse(response, rtDto);
	}
	
	/**
	 * 查詢流程正常走完的历史流程表 :  act_hi_actinst
	 * @param response
	 * @param rows
	 * @param page
	 * @param s_name  
	 * @param groupId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/history/search")
	public void finishedList(DataGridModelUnPaginationInterceptor datagrid, HttpServletResponse response) throws Exception{
		SysUser loginUser = getLoginUser();
		int rows = datagrid.getRows();
		int page = datagrid.getPage();
		int start = datagrid.getStart();
		Map<String, Object> params = datagrid.getParams();
		String applyer = params.isEmpty() ? "" : params.get("applyer").toString().trim();
		
		ResultDto rtDto = new ResultDto();
		//当前页
		int pageNo = start / rows;
											//创建流程历史实例查询
		List<HistoricTaskInstance> histList=historyService.createHistoricTaskInstanceQuery()
				.taskCandidateUser(loginUser.getId()).finished().processFinished()//根据角色名称查询
				.listPage(pageNo, rows);
		
		long histCount=historyService.createHistoricTaskInstanceQuery()
				.taskCandidateUser(loginUser.getId()).finished().processFinished()
				.count();
		List<MyTaskDto> myTaskList=new ArrayList<MyTaskDto>();
		//这里递出没有用的字段，免得给前端页面做成加载压力
		for(HistoricTaskInstance t:histList){
			MyTaskDto myTask=new MyTaskDto();
			myTask.setId(t.getId());
			myTask.setKey(t.getTaskDefinitionKey());
			myTask.setName(t.getName());
			myTask.setProcessDefinitionId(t.getProcessDefinitionId());
			myTask.setCreateTime(t.getStartTime());
			myTask.setEndTime(t.getEndTime());
			HistoricVariableInstance variable = historyService.createHistoricVariableInstanceQuery().processInstanceId(t.getProcessInstanceId()).variableName("billID").singleResult();
			Integer billID = Integer.valueOf(variable.getValue().toString());
			myTask.setBillID(billID);
			String processDefinitionId = t.getProcessDefinitionId();
			if(processDefinitionId.contains("leave")){
				myTask.setProcessName("请假申请");
				OaBillLeaveApplication leave = leaveService.get(billID);
				myTask.setApplyer(leave.getEmplName());
				if(StringUtils.isNotBlank(applyer) && !leave.getEmplName().equals(applyer)){
					continue;
				}
			}else if(processDefinitionId.contains("overtime")){
				myTask.setProcessName("加班申请");
				OaBillOvertimeApplication overtime = overtimeService.get(billID);
				myTask.setApplyer(overtime.getEmplName());
				if(StringUtils.isNotBlank(applyer) && !overtime.getEmplName().equals(applyer)){
					continue;
				}
			}
			myTaskList.add(myTask);
		}
		Pagination data = new Pagination();
		data.setAaData(myTaskList);
		data.setiTotalDisplayRecords((int)histCount);
		data.setiTotalLongRecords(histCount);
		data.setiTotalRecords((int)histCount);
		data.setsEcho(page);
		rtDto.setData(data);
		genResponse(response, rtDto);
	}
	/**
	 * 根据任务id查询流程实例的具体执行过程
	 * @param taskId
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/listAction")
	public void listAction(String taskId,HttpServletResponse response)throws Exception{
		HistoricTaskInstance hti=historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
		String processInstanceId=hti.getProcessInstanceId(); // 获取流程实例id
		List<HistoricActivityInstance> haiList=historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).list();
		
		ResultDto rtDto = new ResultDto();
		rtDto.setData(haiList);
		genResponse(response, rtDto);
	}

	private void genResponse(HttpServletResponse response, ResultDto rtDto) throws IOException {
		JsonConfig jsonConfig=new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss"));
		JSONObject result= JSONObject.fromObject(rtDto, jsonConfig);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println(result.toString());
		out.flush();
		out.close();
	}
    
    public static void main(String[] args) {
    	String elString = "${msg <> 同意}";
    	System.out.println(getParamByElString(elString));
    	//System.out.println(elString.substring(elString.indexOf("{")+1, elString.indexOf("}")));
	}
	
}
